package cn.xiaosiyuan.util.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeUtil {

    public Object invoke(String className,String methodName,Object... args) {
        Object result = null;

        try {
            Class<?> aClass = Thread.currentThread().getContextClassLoader().loadClass("testpackage.TestClass");
            Method[] declaredMethods = aClass.getDeclaredMethods();

            for (int i = 0; i < declaredMethods.length; i++) {
                Method method = declaredMethods[i];
                if(method.getName().equals(methodName)) {

                    // 考虑到重载，invoke失败就找下一个同名的
                    try {
                        result = method.invoke(aClass.newInstance(), args);
                        break;
                    } catch (IllegalAccessException e) {
                        // ignore
                    } catch (IllegalArgumentException e) {
                        // ignore
                    } catch (InvocationTargetException e) {
                        // ignore
                    } catch (InstantiationException e) {
                        // ignore
                    }
                }
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return result;
    }

}
